using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MediatR;
using RBAC.ErrorCode;
using Microsoft.Extensions.Logging;
using RBAC.Read.Api.Application.Command.ERP.SalesReport;
using RBAC.Read.Api.Application.Dto.ERP.SalesReport;
using RBAC.Read.Api.Utils;

namespace RBAC.Read.Api.Controllers.ERP
{/// <summary>
/// 销售报表
/// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SalesReportController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<SalesReportController> _logger;

        public SalesReportController(IMediator mediator, ILogger<SalesReportController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 发货通知明细表（分页、可筛选）
        /// </summary>
        /// <param name="request">查询参数：SalesOrderCode/CustomerName/MaterialName/StartDate/EndDate + PageIndex/PageSize</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>明细表分页结果</returns>
        [HttpGet]
        public Task<APIResult<GetDeliveryNoticeDetailListDto>> GetDeliveryNoticeDetailList(
            [FromQuery] GetDeliveryNoticeDetailListCommand request,
            CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 开票通知明细表（分页、可筛选）
        /// </summary>
        /// <param name="request">查询参数：BillCode/CustomerName/TaxNo/StartDate/EndDate + PageIndex/PageSize</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>明细表分页结果</returns>
        [HttpGet]
        public Task<APIResult<GetBillingNoticeDetailListDto>> GetBillingNoticeDetailList(
            [FromQuery] GetBillingNoticeDetailListCommand request,
            CancellationToken cancellationToken)
        {
            return _mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 导出 开票通知明细（根据筛选条件，不分页）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportBillingNoticeDetail([FromQuery] ExportBillingNoticeDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始导出开票通知明细，筛选: {@Request}", request);
                var bytes = await _mediator.Send(request, cancellationToken);
                if (bytes == null || bytes.Length == 0)
                {
                    return BadRequest("导出数据为空，请检查筛选条件");
                }

                var (safe, display) = FileNameHelper.GenerateBillingNoticeFileName();
                var contentDisposition = FileNameHelper.GenerateContentDisposition(safe, display);
                Response.Headers["Content-Disposition"] = contentDisposition;
                Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
                Response.Headers["Pragma"] = "no-cache";
                Response.Headers["Expires"] = "0";
                Response.Headers["Content-Length"] = bytes.Length.ToString();

                const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(bytes, contentType, safe);
            }
            catch (OperationCanceledException)
            {
                _logger.LogWarning("导出操作被取消");
                return StatusCode(499, "导出操作被取消");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出开票通知明细失败: {Message}", ex.Message);
                return StatusCode(500, $"导出失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导出 发货通知明细表（根据筛选条件，不分页）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportDeliveryNoticeDetail([FromQuery] ExportDeliveryNoticeDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始导出发货通知明细，筛选: {@Request}", request);
                var bytes = await _mediator.Send(request, cancellationToken);
                if (bytes == null || bytes.Length == 0)
                {
                    return BadRequest("导出数据为空，请检查筛选条件");
                }

                var (safe, display) = FileNameHelper.GenerateDeliveryNoticeFileName();
                var contentDisposition = FileNameHelper.GenerateContentDisposition(safe, display);
                Response.Headers["Content-Disposition"] = contentDisposition;
                Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
                Response.Headers["Pragma"] = "no-cache";
                Response.Headers["Expires"] = "0";
                Response.Headers["Content-Length"] = bytes.Length.ToString();

                const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(bytes, contentType, safe);
            }
            catch (OperationCanceledException)
            {
                _logger.LogWarning("导出操作被取消");
                return StatusCode(499, "导出操作被取消");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出发货通知明细失败: {Message}", ex.Message);
                return StatusCode(500, $"导出失败: {ex.Message}");
            }
        }
    }
}
